define(['jquery'], () => {
    class Header {
      constructor () {
        this.loadHTML().then(() => {
          this.calcCartCount()
          this.userName()
          this.search()
        })
      }
      loadHTML () {
        return new Promise(resolve => {
          $('header').load('/web/modules/header.html', resolve)
        })
      }

      calcCartCount () {
        let count = 0
        let cart = localStorage.getItem('cart')
        if (cart) {
          cart = JSON.parse(cart)
          count = cart.reduce((total, shop) => {
            return total + shop.count
          }, 0)
        }
        $('#header-num').html(count)
      }

      userName(){
        var username = document.cookie.split('=')
        var name = decodeURIComponent(username[1])
        if(document.cookie){
          $('.content span span').html(name)
          $('.content span a').show()
          $('.content span a').on('click',()=>{
            var date = new Date()
            date.setDate(date.getDate()-1)
            document.cookie=`name=${name};expires=${date.toUTCString()};path=/`
            localStorage.removeItem('cart')
            $('.content span a').hide()
          })
        }
        else{
          $('.content span span').html('点击登录')
          $('.content span span').on('click',function(){
            location.href = '/web/login.html'
          })
        }
      }

      search(){
        $('#search').on('click',function(){
          var word = $('.main-search input').val()
          console.log(word)
          location.href = `/web/list.html?word=${word}`
        })
      }

    }
    return new Header()
})